package com.blog.servelt;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blog.bean.ArticleBean;
import com.blog.service.BlogService;

/**
 * Servlet implementation class EditArticleServelt
 */
@WebServlet("/EditArticle")
public class EditArticleServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BlogService blogService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditArticleServelt() {
        super();
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id =request.getParameter("id");
		blogService = new BlogService();
		request.getSession().setAttribute("articleId", id);
		ArticleBean bean = blogService.findArticleById(id);
		request.setAttribute("article", bean);
		request.getRequestDispatcher("blogManager/editArticle.jsp").forward(request, response);
		
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		blogService = new BlogService();
		try{
			int userId = (int) request.getSession().getAttribute("userId");
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			String ac_abstract = request.getParameter("ac_abstract");
			String articleId = (String) request.getSession().getAttribute("articleId");
			if(ac_abstract!=null){
				blogService.modifyArticleById(articleId, userId, title, ac_abstract, content);
			}
			request.getSession().removeAttribute("articleId");
			response.sendRedirect(request.getContextPath()+ "/ListArticles");
		}catch(Exception e){
			response.sendRedirect(request.getContextPath());
		}
	}

}
